<template>
  <div class="p-6">
    <el-card class="mb-4" shadow="hover">
      <template #header>
        <div class="flex items-center justify-between">
          <span class="text-xl font-bold text-blue-600">社团信息</span>
        </div>
      </template>
      <el-table :data="tableData" stripe border v-loading="loading.club">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="社团名称" />
        <el-table-column prop="descr" label="社团简介" show-overflow-tooltip />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button type="danger" size="small" @click="handleQuit(scope.row)">退出</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="tableData.length === 0 && !loading.club">
        <el-empty description="暂无社团信息" />
      </div>
    </el-card>

    <el-card class="mb-4" shadow="hover">
      <template #header>
        <div class="flex items-center justify-between">
          <span class="text-xl font-bold text-green-600">社团活动</span>
        </div>
      </template>
      <el-table :data="activities" stripe border v-loading="loading.activities">
        <el-table-column prop="title" label="活动名称" />
        <el-table-column prop="location" label="地点" />
        <el-table-column label="时间">
          <template #default="scope">
            {{ scope.row.startTime }} 至 {{ scope.row.endTime }}
          </template>
        </el-table-column>
        <el-table-column prop="descr" label="描述" show-overflow-tooltip />
        <el-table-column prop="activityType" label="类型" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleViewActivity(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="activities.length === 0 && !loading.activities">
        <el-empty description="暂无活动信息" />
      </div>
    </el-card>

    <el-card shadow="hover">
      <template #header>
        <div class="flex items-center justify-between">
          <span class="text-xl font-bold text-purple-600">通知消息</span>
        </div>
      </template>
      <el-timeline v-loading="loading.notifications">
        <el-timeline-item
          v-for="item in notifications"
          :key="item.id"
          :timestamp="formatTime(item.publishTime)"
          type="primary"
        >
          <div class="flex justify-between items-start">
            <div>
              <h4 class="text-lg font-medium">{{ item.title || '无标题' }}</h4>
              <p class="mt-2 text-gray-600">{{ item.contentText || '无内容' }}</p>
              <p class="mt-1 text-sm text-gray-500">发布社团：{{ item.clubName || '未知社团' }}</p>
            </div>
            <el-button type="primary" size="small" @click="handleViewNotification(item)">查看</el-button>
          </div>
        </el-timeline-item>
      </el-timeline>
      <div v-if="!notifications || notifications.length === 0" class="mt-4">
        <el-empty description="暂无通知" />
      </div>
    </el-card>

    <!-- 活动详情弹窗 -->
    <el-dialog
      v-model="activityDialogVisible"
      title="活动详情"
      width="600px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="活动名称">{{ currentActivity.title }}</el-descriptions-item>
        <el-descriptions-item label="活动地点">{{ currentActivity.location }}</el-descriptions-item>
        <el-descriptions-item label="活动时间">
          {{ currentActivity.startTime }} 至 {{ currentActivity.endTime }}
        </el-descriptions-item>
        <el-descriptions-item label="活动类型">{{ currentActivity.activityType }}</el-descriptions-item>
        <el-descriptions-item label="活动描述">{{ currentActivity.descr }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 通知详情弹窗 -->
    <el-dialog
      v-model="notificationDialogVisible"
      title="通知详情"
      width="600px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="通知标题">{{ currentNotification.title }}</el-descriptions-item>
        <el-descriptions-item label="通知内容">{{ currentNotification.contentText }}</el-descriptions-item>
        <el-descriptions-item label="发布时间">{{ formatTime(currentNotification.publishTime) }}</el-descriptions-item>
        <el-descriptions-item label="发布社团">{{ currentNotification.clubName }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()

// 从 localStorage 获取当前用户信息
const user = JSON.parse(localStorage.getItem('xm-pro-user'))

// 数据状态
const tableData = ref([])
const activities = ref([])
const notifications = ref([])
const loading = reactive({
  club: false,
  activities: false,
  notifications: false
})

const activityDialogVisible = ref(false)
const currentActivity = ref({})
const notificationDialogVisible = ref(false)
const currentNotification = ref({})

// 获取社团列表
const loadData = async () => {
  loading.club = true
  try {
    const { data } = await axios.get(`http://localhost:8080/club/selectByStudentId/${user.id}`)
    console.log('获取到的社团数据:', data) // 添加日志
    tableData.value = data.data || []
    // 社团数据加载完成后，依次加载活动和通知
    await Promise.all([
      fetchActivities(),
      fetchNotifications()
    ])
  } catch (err) {
    console.error('获取社团列表失败:', err) // 添加错误日志
    ElMessage.error('获取社团列表失败')
    tableData.value = []
  } finally {
    loading.club = false
  }
}

// 查看社团详情
const handleView = (row) => {
  router.push({
    name: 'clubs-all-president',
    query: { clubId: row.id }
  })
}

// 获取社团活动
const fetchActivities = async () => {
  loading.activities = true
  try {
    // 获取学生所在的所有社团ID
    const clubIds = tableData.value.map(item => item.id)
    console.log('获取活动使用的社团ID:', clubIds) // 添加日志
    if (clubIds.length === 0) {
      activities.value = []
      loading.activities = false
      return
    }

    // 获取所有社团的活动
    const allActivities = []
    for (const clubId of clubIds) {
      const res = await request.get('/activity/selectAll', {
        params: { clubId }
      })
      console.log(`获取社团 ${clubId} 的活动数据:`, res) // 添加日志
      if (res.code === '200' && Array.isArray(res.data)) {
        allActivities.push(...res.data)
      }
    }
    activities.value = allActivities
    console.log('最终的活动数据:', activities.value) // 添加日志
  } catch (err) {
    console.error('获取活动信息失败:', err) // 添加错误日志
    ElMessage.error('获取活动信息失败')
    activities.value = []
  } finally {
    loading.activities = false
  }
}

// 获取通知消息
const fetchNotifications = async () => {
  loading.notifications = true
  try {
    // 获取学生所在的所有社团ID
    const clubIds = tableData.value.map(item => item.id)
    console.log('获取通知使用的社团ID:', clubIds) // 添加日志

    // 如果有加入的社团，获取社团通知
    if (clubIds.length > 0) {
      const res = await axios.post('http://localhost:8080/notification/selectByClubIds', clubIds)
      console.log('获取社团通知的响应数据:', res) // 添加日志
      if (res.data.code === '200') {
        notifications.value = Array.isArray(res.data.data) ? res.data.data : []
      } else {
        notifications.value = []
      }
    } else {
      notifications.value = []
    }
    console.log('最终的通知数据:', notifications.value) // 添加日志
  } catch (err) {
    console.error('获取通知失败:', err) // 添加错误日志
    ElMessage.error('获取通知信息失败')
    notifications.value = []
  } finally {
    loading.notifications = false
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  // 如果时间格式是 "5.20" 这样的格式，直接返回
  if (time.includes('.')) return time
  // 否则尝试格式化标准时间格式
  try {
    const date = new Date(time)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (e) {
    return time
  }
}

// 查看活动详情
const handleViewActivity = (row) => {
  currentActivity.value = row
  activityDialogVisible.value = true
}

// 查看通知详情
const handleViewNotification = (row) => {
  currentNotification.value = row
  notificationDialogVisible.value = true
}

// 退出社团
const handleQuit = (row) => {
  ElMessageBox.confirm('确定要退出该社团吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.post('/club/quit', {
      clubId: row.id,
      studentId: user.id
    }).then(res => {
      if (res.code === '200') {
        ElMessage.success('退出成功')
        loadData() // 重新加载数据
      } else {
        ElMessage.error(res.msg || '退出失败')
      }
    }).catch(err => {
      console.error('退出社团失败:', err)
      ElMessage.error('退出失败')
    })
  }).catch(() => {
    // 用户取消操作
  })
}

// 页面加载时只调用 loadData
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.mb-4 {
  margin-bottom: 1.5rem;
}

.club-info {
  padding: 1rem;
}

:deep(.el-descriptions__label) {
  width: 120px;
  font-weight: bold;
}

:deep(.el-timeline-item__content) {
  margin-left: 1rem;
}
</style>